<?php
// 接口-库存余额
namespace interface\pda;

use control\outStockExecClass;
use control\inventoryBalanceClass;

class inventoryOtherClass extends index
{
	/**
	 * 账套列表
	 *
	 * @return void
	 */
	public function company(): void
	{
		$this->code         = 1;
		$result             = find(['table' => 'company', 'field' => 'coid as value, name as text']);
		$this->resp['data'] = [
			'option' => $result['array'],
			'now'    => self::findCoid(),
		];
	}
	
	
	/**
	 * 记录当前使用的账套
	 */
	public static function updateCoidRecord($coid): bool
	{
		if (empty($coid)) {
			return false;
		}
		$record = query('user_setting', "stid = '" . self::$stid . "' and type = '当前使用账套'");
		if (empty($record['id'])) {
			$warn = static::insert(array(
				'table' => 'user_setting',
				'field' => [
					'type'  => '当前使用账套',
					'value' => $coid,
					'stid'  => self::$stid,
				],
			));
		} else {
			$warn = static::update(array(
				'table' => 'user_setting',
				'field' => [
					'value' => $coid,
				],
				'where' => "id = '$record[id]'",
			));
		}
		return in_array($warn, ['新增成功', '更新成功']);
	}
	
	
	public function getDefaultFunc()
	{
		$this->code = 1;
		$record     = query('user_setting', "stid = '" . self::$stid . "' and type = 'ERP小程序常用功能'");
		if (!empty($record['id'])) {
			$this->resp['data'] = json_decode($record['value'], true);
		} else {
			static::insert(array(
				'table' => 'user_setting',
				'field' => [
					'type'  => 'ERP小程序常用功能',
					'value' => '{}',
					'stid'  => self::$stid,
				],
			));
			$this->resp['data'] = json_decode('{}');
		}
	}
	
	/**
	 * 更新默认功能
	 */
	public function upDefaultFunc()
	{
		$value = $_POST['func'] ?: '{}';
		$array = json_decode($value, true);
		if (!is_array($array)) {
			$this->resp['warn'] = '更新失败';
		} else {
			$func   = json_encode($array, 320);
			$record = query('user_setting', "stid = '" . self::$stid . "' and type = 'ERP小程序常用功能'");
			if (empty($record['id'])) {
				$warn = static::insert(array(
					'table' => 'user_setting',
					'field' => [
						'type'  => 'ERP小程序常用功能',
						'value' => $func,
						'stid'  => self::$stid,
					],
				));
			} else {
				$warn = static::update(array(
					'table' => 'user_setting',
					'field' => [
						'value' => $func,
					],
					'where' => "id = '$record[id]'",
				));
			}
			if (in_array($warn, ['新增成功', '更新成功'])) {
				$this->resp['warn'] = '更新成功';
				$this->resp['data'] = $array;
				$this->code         = 1;
			} else {
				$this->resp['warn'] = '更新失败';
			}
		}
	}
	
	/**
	 * 切换账套
	 *
	 * @return void
	 */
	public function setCompany(): void
	{
		$coid = $this->post('coid');
		if (!$coid) {
			$this->resp['warn'] = '请选择账套';
		} else {
			$bool = self::updateCoidRecord($coid);
			if ($bool !== true) {
				$this->resp['warn'] = '账套选择失败';
			} else {
				$this->resp['warn'] = '选择成功';
				$this->code         = 1;
			}
		}
	}
	
	/**
	 * 列表仓库
	 *
	 * @return void
	 */
	public function warehouse(): void
	{
		$this->code = 1;
		if (empty(self::$coid)) {
			self::$coid = self::findCoid();
		}
		$result             = find(['table' => 'warehouse', 'field' => 'id as value, name as text', 'where' => " state = '启用' AND coid = '" . self::$coid . "' "]);
		$this->resp['data'] = $result['array'];
	}
	
	/**
	 * 供应商
	 *
	 * @return void
	 */
	public function supplier(): void
	{
		$this->code = 1;
		$items      = outStockExecClass::currentCompany();
		$data       = [];
		foreach ($items as $value => $text) {
			$data[] = [
				'text'  => $text,
				'value' => $value,
			];
		}
		$this->resp['data'] = $data;
	}
	
	/**
	 * 加工单类型
	 *
	 * @return void
	 */
	public function machiningType(): void
	{
		$this->code         = 1;
		$this->resp['data'] = ['生产加工', '生产返工'];
	}
	
	/**
	 * 客户
	 *
	 * @return void
	 */
	public function kehu(): void
	{
		$this->code         = 1;
		$result             = find(['table' => 'kehu', 'field' => 'khid as value, companyName as text', 'where' => " (coid = '" . self::$coid . "' or coid = '') and isDeal = 1 "]);
		$this->resp['data'] = $result['array'];
	}
	
	/**
	 * 选择员工
	 */
	public function staff()
	{
		$this->code         = 1;
		$result             = find([
			'field' => 'stid as value, name as text',
			'table' => 'staff',
		]);
		$this->resp['data'] = $result['array'];
	}
	
	/**
	 * 物料分类
	 *
	 * @return void
	 */
	public function materialType(): void
	{
		$this->code         = 1;
		$result             = find([
			'table' => 'material_type',
			'field' => " id as value, name as text ",
			'where' => generateWhere([
				'coid' => self::$coid,
			]),
		]);
		$this->resp['data'] = $result['array'];
	}
	
	/**
	 * 物料品牌
	 *
	 * @return void
	 */
	public function materialBrand(): void
	{
		$this->code         = 1;
		$result             = find([
			'table' => 'material',
			'field' => "DISTINCT(brand) as text, id as value ",
			'where' => generateWhere([
					'coid'  => self::$coid,
					'state' => '启用',
				]) . " AND brand <> '' ",
		]);
		$this->resp['data'] = $result['array'];
	}
	
	/**
	 * 选择生产线
	 *
	 * @return void
	 */
	public function line(): void
	{
		$this->code         = 1;
		$where              = search([
			'=' => [
				'workshop' => $this->post('workshop') ?: '',
			],
		]);
		$field              = $where ? ' id as value, name as text ' : 'distinct workshop as text';
		$result             = find([
			'table' => 'product_line',
			'field' => $field,
			'where' => generateWhere([
					'coid'  => self::$coid,
					'state' => '启用',
				]) . $where,
		]);
		$this->resp['data'] = $result['array'];
	}
	
	/**
	 * 查找物料
	 *
	 * @return void
	 */
	public function codeByMaterial(): void
	{
		$code = $this->post('code') ?: '';
		$id   = $this->post('orderId') ?: '';
		$waid = $this->post('waid') ?: '';
		$from = $this->post('from') ?: '';
		if (static::isNull($code)) {
			$this->resp['warn'] = '物料条码不能为空';
		} else {
			$materialSku = query('material_sku', " coid = '" . self::$coid . "' AND barcode = '$code' ");
			if (static::isNull($materialSku['id'])) {
				$this->resp['warn'] = '当前账套不存在该物料，请确认';
				return;
			}
			$material     = query('material', " id = '{$materialSku['materialId']}' ");
			$inventoryNum = inventoryBalanceClass::inventoryNum($materialSku['id'], $waid);
			$result       = [
				'mxId'          => self::getId(),
				'materialSkuId' => $materialSku['id'],
				'code'          => $material['code'],
				'name'          => $material['name'],
				'brand'         => $material['brand'],
				'model'         => $material['model'],
				'skuName'       => $materialSku['name'],
				'unit'          => $material['unit'],
				'unitOption'    => inventoryBalanceClass::materialUnit($materialSku['id']),
			];
			$info         = [];
			if ($id && $from) {
				switch ($from) {
					case '入库单':
					case '出库单':
						$table = 'inventory';
						$info  = query($table, " id = '$id' ", 'id, orderNo, IFNULL(orderDate, time) as orderDate, classify, targetId, text');
						if ($info['classify'] == 0) {
							$info['target'] = query('kehu', " khid = '{$info['targetId']}' ")['companyName'];
						} else {
							$info['target'] = query('supplier', " id = '{$info['targetId']}' ")['name'];
						}
						break;
					case '盘点单':
						$table         = 'inventory_take';
						$info          = query($table, " id = '$id' ", 'id, orderNo, warehouse, type as typeId, brand, orderDate, text');
						$info['mtype'] = $info['typeId'] ? inventoryListClass::getTypeName($info['typeId']) : null;
						unset($info['typeId']);
						break;
					case '调拨单':
						$table = 'inventory_allot';
						$info  = query($table, " id = '$id' ", 'id, orderNo, outWarehouse, inWarehouse, orderDate');
						break;
					default:
						$this->resp['warn'] = '类型错误';
						return;
				}
				
				if (static::isNull($info['id'])) {
					$this->resp['warn'] = '此订单信息不存在';
					return;
				}
				$detail = query($table . '_detail', " orderId = '{$info['id']}' AND materialSkuId = '$materialSku[id]' ");
				if (static::isNull($detail['id'])) {
					$this->resp['warn'] = '该订单不存在此物料信息';
					return;
				}
				$result['mxId'] = $detail['id'];
				$result         = array_merge($result, [
					'num'          => $detail['num'],
					'inventoryNum' => $inventoryNum,
					'orderNum'     => $detail['orderNum'] ?: 0,
				]);
			}
			$this->resp['data'] = [
				'info'   => $info,
				'result' => $result,
			];
			$this->code         = 1;
		}
	}
	
	/**
	 * 查找单号
	 *
	 * @return void
	 */
	public function orderByNo(): void
	{
		$orderNo = $this->post('orderNo') ?: '';
		if (static::isNull($orderNo)) {
			$this->resp['warn'] = '单号不能为空';
		} else {
			// 调拨
			if (str_contains($orderNo, 'DB') === true) {
				$info      = query('inventory_allot', " orderNo = '$orderNo' ");
				$source    = 'inventoryAllot';
				$aliasName = '调拨单';
			} // 盘点
			elseif (str_contains($orderNo, 'PD') === true) {
				$info      = query('inventory_take', " orderNo = '$orderNo' ");
				$source    = 'inventoryTake';
				$aliasName = '盘点单';
			} else {
				$info      = query('inventory', " orderNo = '$orderNo' ");
				$source    = 'inventory';
				$aliasName = ($info['classify'] == 0) ? '出库单' : '入库单';
			}
			
			if (static::isNull($info['id'])) {
				$this->resp['warn'] = '单号信息不存在';
			} else {
				$data               = [
					'info'   => $info,
					'source' => $source,
					'from'   => $aliasName,
				];
				$this->resp['data'] = $data;
				$this->code         = 1;
			}
		}
	}
	
}
